package qc.module.ehs.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qc.common.core.exception.QCPromptException;
import qc.common.core.unify.QCUnifyReturnValue;
import qc.module.ehs.entity.EhsTplUnitcategoryHazards;
import qc.module.ehs.repository.EhsTplUnitcategoryHazardsRepository;

import java.util.List;

/**
 * 单元分类接口Service
 *
 * @author QuCheng Tech
 * @create 2024/8/13
 */
@Service
public class EhsTplUnitcategoryHazardsService {
    
    @Autowired
    private EhsTplUnitcategoryHazardsRepository repository;

    /**
     * 删除指定单元分类与危险源清单的关联关系
     * 
     * @param uccd 单元分类代码
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/8/13
     */
    public String deleteByUccd(String uccd){
        if (StringUtils.isBlank(uccd)) return QCUnifyReturnValue.Warn("单元分类代码不能为空");

        LambdaQueryWrapper<EhsTplUnitcategoryHazards> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EhsTplUnitcategoryHazards::getUccd,uccd);
        repository.delete(wrapper);
        return QCUnifyReturnValue.Success();
    }

    /**
     * 添加单元分类与危险源清单关联关系
     *
     * @param uccd 单元分类代码
     * @param hicd 危险源清单ID
     * @author QuCheng Tech
     * @since 2024/8/13
     */
    public String add(String uccd, String hicd) {
        //判断菜单api是否已经关联，如果已经关联则不添加
        if (!hasExist(uccd, hicd)) {
            EhsTplUnitcategoryHazards en = new EhsTplUnitcategoryHazards();
            en.setUccd(uccd);
            en.setHicd(hicd);
            repository.insert(en);
        }
        return QCUnifyReturnValue.Success();
    }

    /**
     * 获取指定单元分类危险源清单ID关联信息
     * 
     * @param uccd 单元代码管理
     * @return List<EhsTplUnitcategoryHazards>
     * @author QuCheng Tech
     * @since 2024/8/13
     */
    public List<EhsTplUnitcategoryHazards> selectByUccd(String uccd) throws QCPromptException {
        if (StringUtils.isBlank(uccd)) throw new QCPromptException("单元分类代码不能为空");
        
        LambdaQueryWrapper<EhsTplUnitcategoryHazards> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EhsTplUnitcategoryHazards::getUccd,uccd);
        List<EhsTplUnitcategoryHazards> ens = repository.selectList(wrapper);
        return ens;
    }

    /**
     * 判断关联关系是否存在
     *
     * @param uccd 单元分类代码
     * @param hicd 危险源清单ID
     * @return boolean
     * @author QuCheng Tech
     * @since 2024/8/13
     */
    public boolean hasExist(String uccd, String hicd) {
        LambdaQueryWrapper<EhsTplUnitcategoryHazards> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EhsTplUnitcategoryHazards::getUccd, uccd);
        wrapper.eq(EhsTplUnitcategoryHazards::getHicd, hicd);

        EhsTplUnitcategoryHazards en = repository.selectOne(wrapper);
        if (en != null)
            return true;

        return false;
    }
}
